package com.zyh.system.supermark1.db;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Author zyh
 * @Description 连接数据库以及关闭数据库连接的方法
 */

public final class JDBCUtil {
    private JDBCUtil() {
    }

    public static String MYSQL_DRIVER;
    public static String URL;
    public static String USERNAME;
    public static String PASSWORD;

    static {
        //通过类加载器读取配置文件
        try {
            InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db_supermarket.properties");
            //创建一个 Properties 集合
            Properties prop = new Properties();
            prop.load(inputStream);
            MYSQL_DRIVER = prop.getProperty("className");
            URL = prop.getProperty("url");
            USERNAME = prop.getProperty("username");
            PASSWORD = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static {
        //加载 MySQL　驱动
        try {
            Class.forName(MYSQL_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 创建连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 关闭资源
    public static void close(Statement statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 关闭资源
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
